import axios from 'axios';
import { LoginRequest, LoginResponse, UploadResponse } from '@/types/api';

// 创建可配置的API实例
const createApi = (baseURL: string) => {
  return axios.create({
    baseURL,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      // 模拟Electron环境的请求头
      'User-Agent': 'Mozilla/5.0 (PicShare Client)',
      'Origin': 'null' // Electron 通常没有 Origin 头
    }
  });
};

// 默认API实例（用于代理）
const defaultApi = createApi('http://localhost:3000');

export const authApi = {
  login: async (data: LoginRequest, serverConfig?: { host: string; port: number }): Promise<LoginResponse> => {
    // 优先使用用户配置的服务器地址
    const baseURL = serverConfig ? `http://${serverConfig.host}:${serverConfig.port}` : 'http://localhost:9500';
    const api = createApi(baseURL);
    
    try {
      const response = await api.post('/api/client/login', data);
      return response.data;
    } catch (error: any) {
      // 如果是跨域错误且是开发环境，尝试使用代理
      if (process.env.NODE_ENV === 'development' && 
          (error.message?.includes('CORS') || error.code === 'ERR_NETWORK')) {
        console.log('使用代理连接服务器');
        const response = await defaultApi.post('/api/client/login', data);
        return response.data;
      }
      throw error;
    }
  }
};

export const uploadApi = {
  upload: async (file: File, apiKey: string, serverConfig?: { host: string; port: number }, onProgress?: (progress: number) => void): Promise<UploadResponse> => {
    // 优先使用用户配置的服务器地址
    const baseURL = serverConfig ? `http://${serverConfig.host}:${serverConfig.port}` : 'http://localhost:9500';
    const api = createApi(baseURL);
    
    try {
      console.log('=== 直接上传到服务器 ===');
      console.log('baseURL:', baseURL);
      console.log('apiKey:', apiKey);

      const formData = new FormData();
      formData.append('file', file);

      const response = await api.post('/api/client/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-API-Key': apiKey
        },
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total && onProgress) {
            const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            onProgress(progress);
          }
        }
      });
      return response.data;
    } catch (error: any) {
      // 如果是跨域错误且是开发环境，尝试使用代理
      if (process.env.NODE_ENV === 'development' &&
          (error.message?.includes('CORS') || error.code === 'ERR_NETWORK')) {
        console.log('=== 使用代理上传文件 ===');
        console.log('传递的 apiKey:', apiKey);
        const formData = new FormData();
        formData.append('file', file);

        const response = await defaultApi.post('/api/client/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'X-API-Key': apiKey
          },
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total && onProgress) {
              const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              onProgress(progress);
            }
          }
        });
        return response.data;
      }
      throw error;
    }
  }
};

export default defaultApi;